<template>
    <view class="container">
        <view class="header-box">
            <view class="header-bg bg-primary" />
            <view class="supplier ptb-25">
                <view class="header">
                    <image :src="easyGetUserImgUrl(supplierInfo.Logo)" mode="" class="supplier-logo"></image>
                    <!-- 供应商列表项start -->
                    <view class="center">
                        <view class="name">{{ supplierInfo.Name }}</view>
                        <!-- 商家标签 -->
                        <view v-if="supplierInfo.TagsList" class="tag-list">
                            <text v-for="(item, index) in supplierInfo.TagsList" :key="index" class="shopTag">{{
                                item.Name
                            }}</text>
                        </view>
                    </view>
                </view>
                <view
                    class="address-box"
                    :style="{
                        backgroundImage: 'url(' + require('@/pages_supplier/static/img/supplier-bg.png') + ')',
                        backgroundSize: '100% 100%',
                    }">
                    <view class="text-show-line-2 mr-20">
                        地址：{{ supplierInfo.ProvinceName || "" }}{{ supplierInfo.CityName || ""
                        }}{{ supplierInfo.RegionName || "" }}{{ supplierInfo.StreetName || ""
                        }}{{ supplierInfo.ContactAddress || "" }}
                    </view>
                    <view
                        v-if="supplierInfo.ContactTel"
                        @click="call(supplierInfo.ContactTel)"
                        class="supplier-tel"
                        :style="{
                            backgroundImage: 'url(' + require('@/pages_supplier/static/img/tel.png') + ')',
                            backgroundSize: '100% 100%',
                        }">
                    </view>
                </view>
            </view>
        </view>
        <search-bar :placeholderText="placeholderText" :actions="actions" @searchFn="searchFn"> </search-bar>
        <!-- tab栏 -->
        <view class="tab-bar zIndexBottom pos-r">
            <view
                v-for="(item, index) in tabItems"
                :key="index"
                class="tab-item"
                :class="tabIndex == index ? 'activeBorder' : ''"
                @click="clickTab(index)">
                <span class="teb-item-text">{{ item.name }}</span>
                <i class="teb-item-border" />
            </view>
        </view>

        <view class="main-dom">
            <swiper class="swiper" :style="{ height: listHeight }" :current="tabIndex" @change="swiperChange">
                <swiper-item v-if="loadOk">
                    <view>
                        <view class="product-main">
                            <scroll-view class="product-main-nav" scroll-y="true" :style="{ height: listHeight }">
                                <nav-tree
                                    :tree-data="classifyList"
                                    :active-id="activeId"
                                    @treeClickEvent="treeClickEvent">
                                </nav-tree>
                            </scroll-view>
                            <view class="product-main-list">
                                <product-list
                                    :ref="'productList'"
                                    :showCartBtn="showCartBtn"
                                    :requestData="requestData"
                                    :supplierId="supplierId"
                                    :height="listHeight"
                                    :isHideProImg="isHideProImg"
                                    @sku="sku"
                                    @amountProp="amountProp"
                                    :displayData="displayData"
                                    @upFavorite="upFavorite"
                                    @isUpNum="isUpNum"
                                    @loadNoMoreBack="loadNoMoreBack">
                                </product-list>
                            </view>
                        </view>
                    </view>
                </swiper-item>
                <swiper-item>
                    <view class="description" v-if="supplierInfo.Description" v-html="supplierInfo.Description"></view>
                    <view class="tac" v-else> 暂无介绍 </view>
                </swiper-item>
                <swiper-item>
                    <image
                        v-if="supplierInfo.LicenseImg"
                        :src="easyGetUserImgUrl(supplierInfo.LicenseImg)"
                        mode=""
                        class="supplier-logo"></image>
                    <view class="" v-else> 暂无资质 </view>
                </swiper-item>
            </swiper>
        </view>
        <bottom-cart :supplierId="supplierId" :supplierStatus="supplierStatus"></bottom-cart>
        <uni-popup type="bottom" ref="popSku" @change="skuChange">
            <product-spec
                v-if="showPopSku"
                :data="optPopup.data"
                :fresh="optPopup.change"
                :popup-type="optPopup.type"
                @closePopup="closePopup"
                @addCart="addCart"
                @addBatch="addBatch"
                @setCarListFunc="setCarListFunc">
            </product-spec>
        </uni-popup>
        <uni-popup ref="popAmountTip" type="center" class="popAmountTip" :animation="false" :maskClick="true">
            <view class="pop-return-box">
                <view class="pop-return-title">
                    <text>输入订购数量</text>
                </view>
                <input confirm-type="search" type="digit" maxlength="10" v-model="popinputAmount" class="btn-input" />
                <view class="pop-action">
                    <view @click="popAmountClose">取消</view>
                    <view @click="popAmountConfirm">确定</view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { mapGetters } from "vuex"
import productList from "@/pages_supplier/components/product/product-list.vue"
import navTree from "@/components/product/nav-tree.vue"
import productSpec from "@/pages_supplier/components/product/product-spec.vue"
import navTreeX from "@/components/product/nav-tree-x.vue"
import numPopup from "@/components/order/num-popup.vue"
import bottomCart from "@/pages_supplier/components/supplier/bottomCart/bottom-cart.vue"
import searchBar from "@/components/common/search-bar.vue"
import { getElementHeight, getElementTop } from "@/uni-sub-base/utils/elementUtil.js"
import { getProductDisplay } from "@/utils/appInit.js"
import utilsOld from "@/utils/utilsOld.js"
import { updateCart, getMarkSupplierCarList, getSupplierCarList } from "@/utils/cartUtil.js"
import config from "@/config/config.js"
import {
    GetSupplier,
    GetSupplierTypeTreeList,
    GetSupplierOffer,
    GetProductDetail,
    ApplySupplierOffter,
} from "@/service/api/supplier.js"
export default {
    components: {
        productList,
        navTree,
        productSpec,
        navTreeX,
        numPopup,
        bottomCart,
        searchBar,
    },
    props: {
        supplierId: {
            type: Number,
            default: 0,
        },
    },
    data() {
        return {
            actions: [],
            // tab
            tabIndex: 0,
            tabItems: [
                {
                    name: "全部商品",
                },
                {
                    name: "商家介绍",
                },
                {
                    name: "商家资质",
                },
            ],
            supplierInfo: {},
            supplierStatus: {},
            showCartBtn: true,
            supplierCartData: {},

            popinputAmount: "",
            inputAmount: "",
            numPopShow: false,
            initClassify: false,
            activeId: -1,
            classifyList: [],
            secondClassifyList: [],
            isFold: true,
            skuModel: false,
            isHideProImg: false,
            actions: [],
            placeholderText: "请输入商品名称",
            searchValue: "",
            tabs: [
                {
                    title: "综合",
                },
                {
                    title: "常购",
                },
                {
                    title: "收藏",
                },
                {
                    title: "促销",
                },
            ],
            navHeight: 0, //nav所需高度
            listHeight: 0, //list所需高度
            listHeight1: 0, //list所需高度
            listHeightNoneSub: 0, //list所需高度
            initHeight: 0,
            productDatas: [],
            navItems: [],
            currentNav: 0,
            isloadding: false,
            loadOk: false,
            // sku 商品规格弹窗
            optPopup: {
                data: {},
                type: "",
                change: false,
                show: true,
            },
            isClosePop: false,
            treeOk: false,
            tags: [],
            brands: [],
            // 请求参数
            requestData: {
                ProductType: 1,
            },
            displayData: {},
            showPopSku: true,
            timer: null,
            isUp: true,
            isShowFilter: false,
            popTop: "",
            popite: {},
            popitem: {},
            poptype: null,
            popdisplayData: {},
            poprefresh: false,
            tagId: "",
            totalClassify: {},
        }
    },
    watch: {
        //监听购物车数据
        getUpView(e) {
            //获取总数
            this.refresh()
        },
        supplierId(id) {
            this.init()
        },
    },
    computed: {
        ...mapGetters(["getUpView"]),
    },
    onShow() {
        //多选规格批量操作回来返回UI处理
        //#ifdef MP
        let pages = getCurrentPages()
        let currPage = pages[pages.length - 1] //当前页
        // 直接用this.currPage.data去取B页面传递过来的数据
        this.isClosePop = currPage.data.isClosePop
        //#endif

        if (this.isClosePop) {
            this.$refs.popSku.close()
            this.isClosePop = false
        }
    },
    mounted() {
        this.init()
        this.getListHeight()

        this.tagId = this.productTagId
    },
    methods: {
        init() {
            this.requestData.supplierId = this.supplierId
            this.GetProductDisplay()
            this.GetSupplier(this.supplierId)
            this.GetSupplierOffer(this.supplierId)
            this.GetSupplierTypeTreeList(this.supplierId)
        },
        // 获取商家详情
        GetSupplier(id) {
            GetSupplier(id).then((res) => {
                if (res && res.Data) {
                    this.supplierInfo = res.Data || {}
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        // 获取商家状态
        GetSupplierOffer(id) {
            GetSupplierOffer(id).then((res) => {
                if (res) {
                    this.supplierStatus = res.Data
                    if (this.ApplySupplierPirce() == 1) {
                        //需要申请
                        if (this.supplierStatus.OfferStatus == 2) {
                            this.showCartBtn = true
                        } else {
                            this.showCartBtn = false
                        }
                    } else {
                        this.showCartBtn.OfferStatus = true
                        this.supplierStatus.OfferStatus == 2
                    }
                }
            })
        },
        // 申请供应商
        apply(status) {
            if (status == 1) {
                this.easyToast("正在审核中，请耐心等待")
            } else if (status == 0) {
                ApplySupplierOffter(this.supplierId).then((res) => {
                    if (res.State) {
                        this.easyToast("申请已提交，等待审核")
                        this.GetSupplierOffer(this.supplierId)
                    } else {
                        this.easyToast(res.Msg)
                    }
                })
            }
        },
        //搜索
        searchFn(searchKey) {
            this.requestData.search = searchKey
            this.refresh()
        },
        // 去结算
        gotoSubmitOrder() {
            let ids = ""
            if (this.supplierCartData && this.supplierCartData.ids && this.supplierCartData.ids != "") {
                ids = this.supplierCartData.ids
                if (ids.charAt(ids.length - 1) == ",") {
                    ids = ids.slice(0, -1)
                }
            } else {
                this.easyToast("当前购物车为空，请添加商品")
                return false
            }
            this.easyGoTo("/pages_supplier/packet/order/submitOrder?ids=" + ids)
        },
        // 拨打电话
        call(tel) {
            uni.makePhoneCall({
                phoneNumber: tel,
            })
        },
        // 获取整体显示设置
        GetProductDisplay() {
            getProductDisplay().then((res) => {
                if (res) {
                    this.displayData = res.Data
                }
            })
        },
        popAmountClose() {
            this.$refs.popAmountTip.close()
        },
        popAmountConfirm() {
            this.inputAmount = this.popinputAmount
            this.popite.Amount = this.popinputAmount
            this.changeAmountFn(this.popite, this.popitem, this.poptype, this.popdisplayData)
        },
        changeAmountFn(item, ite, type, popdisplayData) {
            var that = this
            let num = Number(item.Amount)
            let stock = item.Stock
            let minNum = ite.MinNum
            let UnitRatio = item.Ratio
            let LimitBuy = ite.LimitBuy
            let addNum = ite.AddNum
            const _oldAmount = item.Amount

            if (popdisplayData.NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type)
                } else {
                    item.Amount = num
                }
                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            this.poprefresh = true
            this.$nextTick(() => {
                this.poprefresh = false
            })
            this.$forceUpdate()
            this.isUpNum(false)
            //商品
            if (_oldAmount !== item.Amount || type === 0) {
                const _obj = {}
                _obj.ProductId = item.ProductId
                _obj.Amount = item.Amount
                _obj.SkuId = item.SkuId
                _obj.UnitId = item.UnitId
                _obj.UnitName = item.UnitName
                _obj.Ratio = item.Ratio
                let param = []
                param.push(_obj)
                updateCart(param, false, true).then((res) => {
                    if (res) {
                        this.easyUpTabBarBadge(res)
                    }
                })
            }
            setTimeout((e) => {
                that.$refs.popAmountTip.close()
            }, 500)
        },
        foldToggle() {
            const that = this
            that.isFold = !this.isFold
            that.$nextTick(function () {
                that.getClassifyHeight()
            })
        },
        choseClassify(item) {
            if (this.activeId !== item.id) {
                this.resetClass(item, false)
            }
        },

        //商品分类树列表
        GetSupplierTypeTreeList(supplierId) {
            let param = {
                InfoType: 1,
                parent_path: "_0_2_",
                supplierId: supplierId,
				warehouseId: 0,
				notIds: "",
				categoryType: 0,
				getminorder: 0,
            }
            GetSupplierTypeTreeList(param).then((res) => {
                this.getNavData(res)
            })
        },
        getNavData(res) {
            if (res) {
                this.initClassify = false
                this.classifyList = []
                this.totalClassify = {
                    OrderBy: res.Data.OrderBy,
                    id: res.Data.id,
                    name: res.Data.name,
                    parent_id: res.Data.parent_id,
                    parent_path: res.Data.parent_path,
                    type_id: res.Data.type_id,
                }
                this.classifyList.push(this.totalClassify)
                if (res.Data.children && res.Data.children.length > 0) {
                    res.Data.children.forEach((item) => {
                        this.classifyList.push(item)
                    })
                }
                this.activeId = res.Data.id
                this.typePath = res.Data.parent_path
                this.requestData.typePath = res.Data.parent_path
                setTimeout(() => {
                    this.refresh()
                }, 300)
            }
        },
        //刷新列表
        refresh() {
            this.$refs.productList.refresh(this.requestData)
        },
        getListHeight(element) {
            //获取商品高度
            getElementHeight(this, ".main-dom", (e) => {
                this.initHeight = e - uni.upx2px(140)
                this.listHeight = e - uni.upx2px(140) + "px"
                this.listHeight1 = e - uni.upx2px(140) + "px"
                this.listHeightNoneSub = e - uni.upx2px(140) + "px"
                this.loadOk = true
            })
        },
        getClassifyHeight() {
            if (this.secondClassifyList && this.secondClassifyList.length > 0) {
                const query = uni.createSelectorQuery().in(this)
                query
                    .select(".secondClassify")
                    .boundingClientRect((data) => {
                        this.listHeight1 = Number(this.initHeight) - Number(data.height) + "px"
                    })
                    .exec()
            } else {
                this.listHeight1 = this.listHeightNoneSub
            }
        },

        resetClass(item, bool = true) {
            const that = this
            if (bool) {
                that.secondClassifyList = item.children || []
                that.isFold = true
            } else {
                if (item.children && item.children.length > 0) {
                    that.secondClassifyList = item.children
                    that.isFold = true
                }
            }

            that.activeId = item.id
            that.typePath = item.parent_path
            that.requestData.typePath = item.parent_path

            if (!that.isUp) {
                that.$emit("upCart", true)
                that.isUp = true
            }
            that.$nextTick(function () {
                that.getClassifyHeight()
            })
            that.refresh()
        },
        sku(item) {
            this.showPopSku = true
            this.optPopup.type = "attr"
            this.optPopup.data = item

            this.$refs.popSku.open()
        },
        amountProp(ite, item, type, displayData) {
            this.popite = ite
            this.popitem = item
            this.poptype = type
            this.popdisplayData = displayData
            if (ite.Amount == 0) {
                this.popinputAmount = ""
            } else {
                this.popinputAmount = ite.Amount
            }
            this.$refs.popAmountTip.open()
        },
        addCart(e) {
            this.$refs.popSku.close()
        },
        addCartBatch(e) {},
        addBatch(e) {
            this.$refs.popSku.close()
            this.$refs.popBatch.open()
        },
        buyNow() {},
        swiperChange(e) {
            let tabIndex = e.detail.current
            this.clickTab(tabIndex)
        },
        //tab切换
        clickTab(index) {
            if (this.tabIndex != index) {
                clearTimeout(this.timer)
                this.timer = setTimeout((time) => {
                    this.tabIndex = index
                }, 20)
            }
        },
        // 点击分类事件
        treeClickEvent(item) {
            if (this.activeId !== item.id) {
                this.resetClass(item)
            }
        },
        closePopup() {
            this.$refs.popSku.close()
        },
        setCarListFunc() {
            this.$forceUpdate()
        },
        closePopupBatch() {
            this.$refs.popBatch.close()
        },
        setCarListFuncBatch() {
            this.$forceUpdate()
        },
        skuChange(e) {
            if (!e.show) {
                this.showPopSku = false
            }
        },
        isUpNum(e) {
            this.isUp = e
        },
        loadNoMoreBack(e) {
            if (e) {
                let objItem = {}
                let hasIn = false
                if (this.activeId == this.classifyList[0].id) {
                    //当前是全部分类
                    this.treeClickEvent(this.classifyList[1])
                } else {
                    for (var i = 0; i < this.classifyList.length; i++) {
                        let item = this.classifyList[i]
                        if (item.id == this.activeId) {
                            //判断当前是否是大类
                            this.hasIn = true
                            if (i != this.classifyList.length - 1) {
                                objItem = this.classifyList[i + 1]
                            } else {
                                objItem = this.classifyList[0]
                            }
                            this.treeClickEvent(objItem)
                            return
                        }
                    }
                    if (!hasIn) {
                        for (var i = 1; i < this.classifyList.length; i++) {
                            let item = this.classifyList[i]
                            let path = item.parent_path
                            if (this.typePath.includes(path)) {
                                let item = this.classifyList[i]
                                if (i != this.classifyList.length - 1) {
                                    objItem = this.classifyList[i + 1]
                                } else {
                                    objItem = this.classifyList[0]
                                }
                                this.treeClickEvent(objItem)
                                return
                            }
                        }
                    }
                }
            }
        },
    },
}
</script>

<style lang="scss" scoped>
/deep/img {
    width: 100%;
}

.header-box {
    position: relative;
    padding-top: 24rpx;

    .header-bg {
        position: absolute;
        background: $app-color-main;
        width: 100%;
        height: 150rpx;
        top: 0;
        left: 0;
    }

    .supplier {
        background: #fff;
        border-radius: 16rpx;
        margin: 24rpx;
        padding: $app-page-padding 0;
        margin-top: 0;
        position: relative;
        box-shadow: 0px 0px 8rpx 0rpx rgba(0, 0, 0, 0.1);

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 $app-page-padding;

            .supplier-logo {
                width: 96rpx;
                height: 96rpx;
                border-radius: 8rpx;
            }

            .center {
                min-height: 96rpx;
                box-sizing: border-box;
                padding: 0 10rpx 52rpx;
                flex-grow: 1;
                position: relative;
                padding-left: 20rpx;
            }

            .name {
                font: $font-size-32;
                line-height: 1;
                font-weight: 500;
                padding: 5rpx;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: 1;
            }

            .tag-list {
                position: absolute;
                width: 100%;
                bottom: 0;
                display: flex;
                flex-wrap: wrap;
                overflow: hidden;
                max-height: 42rpx;
            }

            .shopTag {
                font-size: 20rpx;
                line-height: 30rpx;
                height: 32rpx;
                min-width: 100rpx;
                text-align: center;
                color: #f53b1c;
                border-radius: 8rpx;
                border: 1rpx solid currentColor;
                padding: 0 10rpx;
                margin: 0 10rpx 10rpx 0;
            }

            button {
                height: 56rpx;
                line-height: 56rpx;
                font-size: 26rpx;
                padding: 0 30rpx;
                border-radius: 28rpx;
                background: $app-color-main;
                color: #fff;
            }
        }

        .address-box {
            min-height: 72rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 25rpx;
            padding: 20rpx 25rpx;

            .mr-20 {
                margin-right: 20rpx;
            }

            .supplier-tel {
                flex-shrink: 0;
                width: 48rpx;
                height: 48rpx;
            }
        }
    }
}

.tab-bar {
    display: flex;

    flex-direction: row;
    // background: $colorF;
    padding: 20rpx 0;

    .tab-item {
        display: flex;
        justify-content: center;
        padding: 0 26rpx;
        align-items: center;
        flex-direction: column;

        .teb-item-text {
            display: flex;
            font-size: 26rpx;
            font-weight: bold;
            margin-bottom: 10rpx;
        }

        .teb-item-border {
            display: flex;
            width: 80rpx;
            height: 6rpx;
            border-radius: 3rpx;
            background: rgba($color: #000000, $alpha: 0);
        }
    }

    .activeBorder {
        .teb-item-text {
            color: $app-color-main;
        }

        .teb-item-border {
            background: $app-color-main;
        }
    }
}

.product-main {
    display: flex;
    flex-direction: row;

    .product-main-nav {
        display: flex;
        flex: 1.1;
        flex-direction: column;
        background: #f7f7f7;
    }

    .product-main-list {
        // display: flex;
        flex: 3.5;
        // justify-content: center;
        background: $uni-bg-color-grey;
    }

    .p-b-120 {
        padding-bottom: 120rpx;
    }
}

.swiper {
    background: $color-white;
}

.product-main-1 {
    .product-main-list {
        padding: 0 $app-page-padding;
        background: $uni-bg-color-grey;
    }

    .p-b-120 {
        padding-bottom: 120rpx;
    }
}

.nav-bar {
    display: flex;
    height: 88rpx;
    flex: 1;
    align-items: center;
    justify-content: space-between;
    background: $color-white;
    border-bottom: solid 1rpx $line;

    .nav-bar-scroll {
        display: flex;
        flex-direction: row;
        width: calc(100% - 110rpx);
    }

    .nav-bar-action {
        display: flex;
        flex-direction: row;
        align-items: center;

        .line {
            width: 1rpx;
            height: 26rpx;
            background: #ccc;
        }

        .filter-box {
            min-width: 60rpx;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 0 28rpx;

            .filter-box-icon {
                display: flex;
            }

            .filter-box-text {
                font-size: $font-size-20;
            }
        }
    }
}

.secondClassify {
    width: 100%;
    box-sizing: border-box;
    background: $color-white;
    display: flex;
    flex-wrap: nowrap;
    padding: 32rpx 50rpx 0 20rpx;
    position: relative;

    .secondClassify-item {
        flex-shrink: 0;
        flex-grow: 0;
        padding: 6rpx 16rpx;
        font-size: $font-size-26;
        line-height: 1.5;
        background-color: $color-gray-5;
        border-radius: 42rpx;
        margin: 0 24rpx 24rpx 0;
    }

    .active-item {
        color: $color-white;
        background: $color-main;
    }

    .fold-icon {
        position: absolute;
        width: 50rpx;
        height: 50rpx;
        top: 32rpx;
        right: 0;
        background: $color-white;

        // background: #eee;
        &:after {
            content: "";
            position: absolute;
            top: 10rpx;
            left: 14rpx;
            width: 15rpx;
            height: 15rpx;
            transform: rotate(45deg);
            border: 2rpx solid;
            border-color: transparent $color-gray-3 $color-gray-3 transparent;
        }
    }

    .unfold-icon {
        &:after {
            transform: rotate(-135deg);
            top: 20rpx;
        }
    }
}

.secondClassify-unfold {
    flex-wrap: wrap;
}

.description {
    overflow: auto;
    height: 100%;
    padding-bottom: 130rpx;
    box-sizing: border-box;
}
</style>
